//
//  TSMsgEditTableViewController.m
//  chart
//
//  Created by xu on 15/8/13.
//  Copyright (c) 2015年 xu. All rights reserved.
//

#import "TSTaskIngDetailController.h"
#import "TSMsgContentItemCell.h"
#import "TSPickerViewTextFieldCell.h"
#import "TSTaskModel.h"
#import "TSReceiveMsgEditExtendStepViewController.h"
#import "TSFileTools.h"
#import "TSSpiltTaskController.h"
#import "TSCreateTaskController.h"
#import "TSUserController.h"
#import "TSTaskProgressController.h"
#import "TSSuggestController.h"
#import "TSCommitEditContentController.h"
#import "TSSuggestEditContentController.h"
#import "TSTaskWebMainDetailController.h"
#import "TSMutipleCheckTableViewController.h"
@interface TSMsgEditTableViewController ()<UIDocumentInteractionControllerDelegate>

@end

@implementation TSTaskIngDetailController{
    NSArray *dataArray;
    NSArray *dataEntrustArray;
    NSArray *dataVacateArray;
    
    NSArray *actionArray;
    QSFetchModel *actionModel;
    TSTaskModel *mTaskModel;
    TSTaskModel *mTaskModel2;
    UIDocumentInteractionController *docInteractionController;
}

@synthesize taskId,taskModel,isAudit;

- (void)viewDidLoad {
    [super viewDidLoad];
    
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onMultipleSelectCompelete:) name:TSNotification_OnMultipleSelectCompelete object:nil];
    
    UIBarButtonItem *right_btn_item = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"topic_follow_add"] style:UIBarButtonItemStyleDone target:self action:@selector(onRightItemClick:)];
    self.navigationItem.rightBarButtonItem = right_btn_item;
    
    mTaskModel = [[TSTaskModel alloc] init];
    dataArray = @[@"标题:",@"内容:",@"开始时间:",@"结束时间:",@"主办人:", @"类型:",@"附件:"];
    WS(weakSelf);
    
    mTaskModel.requestParams = @{TSDictionaryKeyDefine_Id:taskModel.taskId?taskModel.taskId:taskModel.tId};
    [mTaskModel fetchWithPath:kRequestUrl_Task_outOne_detail completionHandler:^(BOOL isSucceeded, NSError *error) {
        if (!weakSelf) {
            return;
        }
        [weakSelf.tableView reloadData];
    } NoProgress:NO];
}

- (void)onRightItemClick:(id)sender
{
    UIActionSheet *action_sheet = [self createActionSheet];
    [action_sheet showInView:self.view];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

-(UIActionSheet *)createActionSheet
{
   WS(weakSelf);
   return [[UIActionSheet alloc] initWithTitle:nil delegate:weakSelf cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"查看进度",@"查看审核人",@"查看监督人",@"查看建议列表", nil];
}

#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
     if(buttonIndex == 0){
       [self getProgress];
     }else if(buttonIndex == 1){
         [self showAuditors];
     }else if(buttonIndex == 2){
         [self showSupervisers];
     }else if(buttonIndex == 3){
         [self showSuggest];
     }
}

//查看任务主线
-(void)showTaskWebMain{
    TSTaskWebMainDetailController * col = [[TSTaskWebMainDetailController alloc] init];
    TSBaseNavigationController *nav = [[TSBaseNavigationController alloc] initWithRootViewController:col];
    [self presentViewController:nav animated:YES completion:nil];
}
//添加监督人
-(void)addSuperviors{
    TSMutipleCheckTableViewController *multiple_vc = [[TSMutipleCheckTableViewController alloc] init];
    multiple_vc.toolBarTextFieldType = ToolBarTextField_Type_AddSupervise;
    TSBaseNavigationController *nav = [[TSBaseNavigationController alloc] initWithRootViewController:multiple_vc];
    [self presentViewController:nav animated:YES completion:nil];
}

//查看建议列表
-(void)showSuggest{
    TSSuggestController *su_col = [[TSSuggestController alloc] init];
    su_col.taskId =mTaskModel.tId;
    [self.navigationController pushViewController:su_col animated:YES];
}

//查看审核人
-(void)showAuditors{
    TSUserController *userCol = [[TSUserController alloc] init];
    userCol.mTitle = @"审核人列表";
    userCol.requestUrl = kRequestUrl_Task_outList_detail_auditList;
    userCol.extData = @{@"id":taskModel.tId};
    [self.navigationController pushViewController:userCol animated:YES];
}
//查看监督人
-(void)showSupervisers{
    TSUserController *userCol = [[TSUserController alloc] init];
    userCol.mTitle = @"监督人列表";
    userCol.requestUrl = kRequestUrl_Task_outList_detail_superviseList;
    userCol.extData = @{@"id":taskModel.tId};
    [self.navigationController pushViewController:userCol animated:YES];
}
//查看点赞人
-(void)showPraisers{
    TSUserController *userCol = [[TSUserController alloc] init];
    userCol.mTitle = @"点赞人列表";
    userCol.requestUrl = kRequestUrl_Task_outList_detail_praiseList;
    userCol.extData = @{@"id":taskModel.tId};
    [self.navigationController pushViewController:userCol animated:YES];
}
-(void) splitTask
{
    if(mTaskModel.changeNext==0){
        [TSTools showAlert:@"任务已下发"];
    }else{
        //拆分任务
        TSSpiltTaskController * spilt_vc= [[TSSpiltTaskController alloc] init];
        spilt_vc.taskId = mTaskModel.tId;
        spilt_vc.mTaskModel = mTaskModel;
        [self.navigationController pushViewController:spilt_vc animated:YES];
    }
}
-(void)getProgress{
    TSTaskProgressController *tpc = [[TSTaskProgressController alloc] init];
    tpc.id = mTaskModel.tId;
    [self.navigationController pushViewController:tpc animated:YES];
}

-(void) sendTask
{
    WS(weakSelf);
    taskModel.requestParams =@{TSDictionaryKeyDefine_Id:taskModel.taskId?taskModel.taskId:taskModel.tId};
    [taskModel fetchWithPath:kRequestUrl_Task_Action_Send completionHandler:^(BOOL isSucceeded, NSError *error) {
        if (!weakSelf) {
            return;
        }
        [weakSelf.navigationController popToRootViewControllerAnimated:YES];
    } NoProgress:NO];
}
-(void) commitTask
{
    TSCommitEditContentController *commit_col = [[TSCommitEditContentController alloc] init];
    commit_col.taskId = taskModel.taskId?taskModel.taskId:taskModel.tId;
    [self.navigationController pushViewController:commit_col animated:YES];
   }
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [dataArray count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *title = [dataArray objectAtIndex:indexPath.row];
    if([title isEqualToString:@"内容:"]){
        return 200;
    }else{
        return CELL_HEIGHT;
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *title = [dataArray objectAtIndex:indexPath.row];
    
     if ([title isEqualToString:@"附件:"]){
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuseIdentifier"];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"reuseIdentifier"];
            
            UIButton *btn = [self createButton:CGRectMake(100.f, MARGIN_TOP, 100.f, CELL_HEIGHT-2*MARGIN_TOP) WithTitle:@"下载附件"];
            [btn.titleLabel setFont:FONT(12.f)];
            [cell.contentView addSubview:btn];
        }
        cell.textLabel.text = title;
        [cell.textLabel setFont:FONT(12.f)];
        
        return cell;
    }
     else if([title isEqualToString:@"图片:"]){
         
     }
    else{
        TSMsgContentItemCell *content_cell = [tableView dequeueReusableCellWithIdentifier:@"contentCell"];
        if (!content_cell) {
            content_cell = [[TSMsgContentItemCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"contentCell"];
        }
        [content_cell setTitleAndTextField:title Type:UITextFieldDefault];
        [content_cell setTextFieldEditable:NO];
        [content_cell.contentTextField setText:[self getTextByTitle:[dataArray objectAtIndex:indexPath.row]]];
        if([title isEqualToString:@"内容:"]){
            content_cell.contentTextField.frame=CGRectMake( content_cell.contentTextField.frame.origin.x,  content_cell.contentTextField.frame.origin.y, content_cell.contentTextField.frame.size.width, 200);
        }
        return content_cell;
    }
    return nil;
}


- (NSString *)getTextByTitle:(NSString *)title
{
    NSString *result_text = @"";
    if (taskModel) {
        if ([title isEqualToString:@"标题:"]) {
            result_text = mTaskModel.title;
        }
        else if ([title isEqualToString:@"开始时间:"]){
            result_text = [TSTools getDateByTime:mTaskModel.timeBegin];
        }
        else if ([title isEqualToString:@"结束时间:"]){
            result_text = [TSTools getDateByTime:mTaskModel.timeEnd];
        }
        else if ([title isEqualToString:@"内容:"]){
            result_text = mTaskModel.content;
        }
        else if ([title isEqualToString:@"主办人:"]){
            result_text = mTaskModel.receiveName;
        }
        else if ([title isEqualToString:@"类型:"]){
            result_text = [TSTools getTaskTypeString:mTaskModel.taskLevel];
        }
    }
    
    return result_text;
}

- (UIButton *)createButton:(CGRect)frame WithTitle:(NSString *)title
{
    UIButton *btn = [[UIButton alloc] initWithFrame:frame];
    [btn setTitle:title forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(onBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    btn.layer.borderColor = [UIColor lightGrayColor].CGColor;
    btn.layer.borderWidth = .5f;
    
    return btn;
}

- (void)onBtnClick:(UIButton *)btn
{
    
    if(mTaskModel.sendAttachment.count<=0){
        [TSTools showAlert:@"无附件下载"];
    }else{
        [[LBToastManager manager] showprogress:nil];
        TSFileModel *fileModel = [mTaskModel.sendAttachment objectAtIndex:0];
        //        [TSFileTools downloadFileURL:[NSString stringWithFormat:@"%@:80%@", BASE_URL,@"/test/a.a"] savePath:[TSFileTools getCacheFileDir] fileName:fileModel.upload tag:0];
        [TSFileTools download:[NSString stringWithFormat:@"%@:80%@", BASE_URL,fileModel.download] name:fileModel.upload downloadHandler:^(NSString * path){
            //[TSTools showAlert:@"下载成功"];
            //[TSFileTools openMenu:self.view delete:self filePath:path];
            
            [ self setupDocumentControllerWithURL:[NSURL fileURLWithPath:path]];
            
            CGRect rect = CGRectMake ( 0 , 0 , currentDeviceWidth , 200 );
            
            //    [self.docInteractionController presentOptionsMenuFromRect:rect inView:self.view  animated:YES];//包含快速预览菜单
            
            [docInteractionController presentOpenInMenuFromRect :rect inView : self.view animated : YES ]; //不包含包含快速预览菜单
            [[LBToastManager manager] hideprogress];
        }];
    }
    
}

- ( void )setupDocumentControllerWithURL:( NSURL *)url

{
    
    if ( docInteractionController == nil ){
        
        docInteractionController=[UIDocumentInteractionController interactionControllerWithURL :url];
        
        docInteractionController.delegate = self ;
        
    }
    
    else {
        
        docInteractionController.URL = url;
        
    }
    
}

- (UITableViewCell *)getCellByTitle:(NSString *)title
{
    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:[self getIndexPathByTitle:title]];
    return cell;
}

- (NSIndexPath *)getIndexPathByTitle:(NSString *)title
{
    if (dataArray) {
        for (int i=0; i<dataArray.count; i++) {
            if ([[dataArray objectAtIndex:i] isEqualToString:title]) {
                NSIndexPath *index_path = [NSIndexPath indexPathForItem:i inSection:0];
                return index_path;
            }
        }
    }
    
    return nil;
}

- ( UIViewController *)documentInteractionControllerViewControllerForPreview:( UIDocumentInteractionController *)interactionController{
    
    return self ;
    
}

// 不显示 copy print

- ( BOOL )documentInteractionController:( UIDocumentInteractionController *)controller canPerformAction:( SEL )action{
    
    return NO ;
    
}

- ( BOOL )documentInteractionController:( UIDocumentInteractionController *)controller performAction:( SEL )action{
    
    return NO ;
    
}

-(void)makeSuggest{
    TSSuggestEditContentController * edit_col = [[TSSuggestEditContentController alloc] init];
    edit_col.taskId = self.taskModel.tId;
    [self.navigationController pushViewController:edit_col animated:YES];
}


- (void)onMultipleSelectCompelete:(NSNotification *)noti
{
    NSArray *names = [noti.object objectForKey:TSDictionaryKeyDefine_Name];
    NSNumber *type  = (NSNumber *)[noti.object objectForKey:TSDictionaryKeyDefine_Type];
    
    if (type.integerValue == ToolBarTextField_Type_AddSupervise) {
        NSString * ids = [self getIds:names];
        //发起添加监督人请求
        WS(weakSelf);
        mTaskModel2 = [[TSTaskModel alloc] init];
        mTaskModel2.requestParams = @{TSDictionaryKeyDefine_Id:taskModel.taskId?taskModel.taskId:taskModel.tId,TSDictionaryKeyDefine_SuperviseIds:ids};
        [mTaskModel2 fetchWithPath:kRequestUrl_Task_action_superviseAdd completionHandler:^(BOOL isSucceeded, NSError *error) {
            if (!weakSelf) {
                return;
            }
            [weakSelf.navigationController popToRootViewControllerAnimated:YES];
            
        } NoProgress:NO];
    }
    
}


- (NSString *)getIds:(NSArray *)names
{
    NSMutableString *name_str = [[NSMutableString alloc] initWithString:@""];
    if (names && names.count > 0) {
        
        for (int i=0; i<names.count; i++) {
            TSUserModel *model = [names objectAtIndex:i];
            [name_str appendString:model.userId];
            
            if (i < names.count-1) {
                [name_str appendString:@","];
            }
        }
    }
    
    return name_str;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
